const {} = require("../constant/err.type");
const {
  createNumber,
  updateNumber,
  removeNumber,
  restoreNumber,
  findNumber,
} = require("../service/number.service");
const {
  NUMBER_CREATE_ERROE,
  NUMBER_MODIFICATION_FAILED,
  NUMBER_ID_NOT_PRESENT,
  NUMBER_REMOVE_ERROR,
  NUMBER_RESTORE_ERROR,
  NUMBER_GET_ERROR,
} = require("../constant/err.type");

class NumberController {
  async create(ctx) {
    try {
      const res = await createNumber(ctx.request?.body);
      ctx.body = {
        code: 0,
        msg: "号码创建成功",
        data: {
          id: res.id,
          numberName: res.numberName,
          numberNumber: res.numberNumber,
        },
      };
    } catch (error) {
      console.error(NUMBER_CREATE_ERROE.msg, error);
      ctx.app.emit("error", NUMBER_CREATE_ERROE, ctx);
    }
  }

  async update(ctx) {
    try {
      const res = await updateNumber(ctx.params?.id, ctx.request?.body);
      if (res) {
        ctx.body = {
          code: 0,
          msg: "号码修改成功",
          data: null,
        };
      } else {
        console.error(
          NUMBER_ID_NOT_PRESENT.msg,
          ctx.params?.id,
          ctx.request?.body
        );
        ctx.app.emit("error", NUMBER_ID_NOT_PRESENT, ctx);
      }
    } catch (error) {
      console.error(NUMBER_MODIFICATION_FAILED.msg, error);
      ctx.app.emit("error", NUMBER_MODIFICATION_FAILED, ctx);
    }
  }

  async remove(ctx) {
    try {
      const res = await removeNumber(ctx.params?.id);
      if (res) {
        ctx.body = {
          code: 0,
          msg: "号码下架成功",
          data: null,
        };
      } else {
        console.error(NUMBER_ID_NOT_PRESENT.msg, ctx);
        ctx.app.emit("error", NUMBER_ID_NOT_PRESENT, ctx);
      }
    } catch (error) {
      console.error(NUMBER_REMOVE_ERROR.msg, error);
      ctx.app.emit("error", NUMBER_REMOVE_ERROR, ctx);
    }
  }

  async restore(ctx) {
    try {
      const res = await restoreNumber(ctx.params?.id);
      if (res) {
        ctx.body = {
          code: 0,
          msg: "号码上架成功",
          data: null,
        };
      } else {
        console.error(NUMBER_ID_NOT_PRESENT.msg, ctx);
        ctx.app.emit("error", NUMBER_ID_NOT_PRESENT, ctx);
      }
    } catch (error) {
      console.error(NUMBER_RESTORE_ERROR.msg, error);
      ctx.app.emit("error", NUMBER_RESTORE_ERROR, ctx);
    }
  }

  async findAll(ctx) {
    try {
      const { page = 1, pageSize = 10 } = ctx.request.query;
      const res = await findNumber(page, pageSize);
      ctx.body = {
        code: 0,
        msg: "获取数据成功",
        data: res,
      };
    } catch (error) {
      console.error(NUMBER_GET_ERROR.msg, error);
      ctx.app.emit("error", NUMBER_GET_ERROR, ctx);
    }
  }
}

module.exports = new NumberController();
